/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.relsell.mediacontroller;

import java.lang.ref.WeakReference;
import java.util.Formatter;
import java.util.Locale;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.relsell.mediacontroller.RangeSeekBarNet.OnRangeSeekBarChangeListener;

/**
 * A view containing controls for a MediaPlayer. Typically contains the
 * buttons like "Play/Pause", "Rewind", "Fast Forward" and a progress
 * slider. It takes care of synchronizing the controls with the state
 * of the MediaPlayer.
 * <p>
 * The way to use this class is to instantiate it programatically.
 * The MediaController will create a default set of controls
 * and put them in a window floating above your application. Specifically,
 * the controls will float above the view specified with setAnchorView().
 * The window will disappear if left idle for three seconds and reappear
 * when the user touches the anchor view.
 * <p>
 * Functions like show() and hide() have no effect when MediaController
 * is created in an xml layout.
 * 
 * MediaController will hide and
 * show the buttons according to these rules:
 * <ul>
 * <li> The "previous" and "next" buttons are hidden until setPrevNextListeners()
 *   has been called
 * <li> The "previous" and "next" buttons are visible but disabled if
 *   setPrevNextListeners() was called with null listeners
 * <li> The "rewind" and "fastforward" buttons are shown unless requested
 *   otherwise by using the MediaController(Context, boolean) constructor
 *   with the boolean set to false
 * </ul>
 */
public class VideoOptionsView extends FrameLayout {
    private static final String TAG = "VideoControllerView";
    MediaPlayer mPlayer;
    private Context             mContext;
    private ViewGroup           mAnchor;
    private View                mRoot;
    private boolean             mShowing;
    private static final int    sDefaultTimeout = 3000;
    private static final int    FADE_OUT = 1;
    private static final int    SHOW_PROGRESS = 2;
    StringBuilder               mFormatBuilder;
    private ImageButton         mPauseButton;
    Formatter                   mFormatter;
    private Button mButton2;
    
    protected boolean isVideoCompleted;
    
    private SeekBar mSeekBarOne;
    private long milliPlayerMinValue;
    private long milliPlayerMaxValue;
    
    private int mPlayerMinValue;
    private int mPlayerMaxValue;
    protected Integer minSeekBarValue;
	protected Integer maxSeekBarValue;
    
    

    private Handler             mHandler = new MessageHandler(this);
    
    public OnClickListener mOnClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			mRoot.findViewById(R.id.LinearLayoutRoot).setVisibility(View.VISIBLE);
			mPlayer.pause();
			
		}
	};

    public VideoOptionsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mRoot = null;
        mContext = context;
        
        Log.i(TAG, TAG);
    }
    
    private void startVideoPlayerWithinBounds() {
    	final int startSec = mPlayerMinValue * 60 ;
    	if(isVideoCompleted) {
    		mPlayer.start();
    		isVideoCompleted = false;
    	}
    	mPlayer.seekTo(startSec);
    }
    
    public VideoOptionsView(Context context, boolean useFastForward) {
        super(context);
        mContext = context;
        
        Log.i(TAG, TAG);
        
    }

    public VideoOptionsView(Context context) {
        this(context, true);

        Log.i(TAG, TAG);
    }

    @Override
    public void onFinishInflate() {
        if (mRoot != null)
            initControllerView(mRoot);
    }
    
    

    /**
     * Set the view that acts as the anchor for the control view.
     * This can for example be a VideoView, or your Activity's main view.
     * @param view The view to which to anchor the controller when it is visible.
     */
    public void setAnchorView(ViewGroup view) {
        mAnchor = view;

        FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );

        removeAllViews();
        View v = makeControllerView();
        addView(v, frameParams);
    }

    /**
     * Create the view that holds the widgets that control playback.
     * Derived classes can override this to create their own.
     * @return The controller view.
     * @hide This doesn't work as advertised
     */
    protected View makeControllerView() {
        LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mRoot = inflate.inflate(R.layout.video_options, null);
        mButton2 = (Button)mRoot.findViewById(R.id.button2);
        mSeekBarOne = (SeekBar)mRoot.findViewById(R.id.seekBar1);
        mButton2.setOnClickListener(mOnClickListener);
        initControllerView(mRoot);
        return mRoot;
    }

    private void initControllerView(View v) {
 
        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
        mPauseButton = (ImageButton) v.findViewById(R.id.pause);
      //  minSeekBar = (SeekBar)v.findViewById(R.id.seekBar1);
      //  maxSeekBar = (SeekBar)v.findViewById(R.id.seekBar2);
        
        if (mPauseButton != null) {
            mPauseButton.setOnClickListener(mPauseListener);
        }
       
		
        
        

    }
    
    public void updatePausePlay() {
        if (mRoot == null || mPauseButton == null || mPlayer == null) {
            return;
        }

        if (mPlayer.isPlaying()) {
            mPauseButton.setImageResource(R.drawable.ic_media_pause);
        } else {
            mPauseButton.setImageResource(R.drawable.ic_media_play);
        }
    }
    
    private void doPauseResume() {
//        if (mPlayer == null) {
//            return;
//        }
//        if (mPlayer.isPlaying()) {
//            mPlayer.pause();
//        } else {
//            mPlayer.start();
//        }
//        updatePausePlay(); 
    	  mPlayer.seekTo(mPlayerMinValue*1000);
    	  mPlayer.start();
        
    }
    
    
    
    private View.OnClickListener mPauseListener = new View.OnClickListener() {
        public void onClick(View v) {
        	mSeekBarOne.setVisibility(View.VISIBLE);
        	mSeekBarOne.setProgress(0);
            mSeekBarOne.setMax(1000);
            mPlayer.start();
            mPlayer.seekTo(minSeekBarValue);
            new PlayVideoTask().execute();
        }
    };
	
	
    /**
     * Show the controller on screen. It will go away
     * automatically after 3 seconds of inactivity.
     */
    public void show() {
        show(sDefaultTimeout);
    }

    
    /**
     * Show the controller on screen. It will go away
     * automatically after 'timeout' milliseconds of inactivity.
     * @param timeout The timeout in milliseconds. Use 0 to show
     * the controller until hide() is called.
     */
    public void show(int timeout) {
        if (!mShowing && mAnchor != null) {
            

            FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                Gravity.TOP
            );
            
            mAnchor.addView(this, tlp);
            mShowing = true;
        }
        
        // cause the progress bar to be updated even if mShowing
        // was already true.  This happens, for example, if we're
        // paused with the progress bar showing the user hits play.
        mHandler.sendEmptyMessage(SHOW_PROGRESS);

        Message msg = mHandler.obtainMessage(FADE_OUT);
        if (timeout != 0) {
            mHandler.removeMessages(FADE_OUT);
            mHandler.sendMessageDelayed(msg, timeout);
        }
    }
    public void setPlayer(MediaPlayer player) {
 	   this.mPlayer = player;
 	  int minRange = 0;
      int maxRange = 1000;
      RangeSeekBarNet<Integer> seekBar = new RangeSeekBarNet<Integer>(minRange,maxRange, mContext);
		seekBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {

			@Override
			public void onRangeSeekBarValuesChanged(RangeSeekBarNet<?> bar,
					Integer minValue, Integer maxValue) {
				// handle changed range values
				Log.i(TAG, "User selected new range values: MIN=" + minValue
						+ ", MAX=" + maxValue);
				minSeekBarValue = minValue;
				maxSeekBarValue = maxValue;
			}
		});

		// add RangeSeekBar to pre-defined layout
		ViewGroup layout = (ViewGroup) mRoot.findViewById(R.id.LinearLayout);
		layout.addView(seekBar);
        
 	   
 	   
 		
 	}
    
    public boolean isShowing() {
        return mShowing;
    }

    /**
     * Remove the controller from the screen.
     */
    public void hide() {
        if (mAnchor == null) {
            return;
        }

        try {
            mAnchor.removeView(this);
            mHandler.removeMessages(SHOW_PROGRESS);
        } catch (IllegalArgumentException ex) {
            Log.w("MediaController", "already removed");
        }
        mShowing = false;
    }

    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours   = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        show(sDefaultTimeout);
        return true;
    }

    @Override
    public boolean onTrackballEvent(MotionEvent ev) {
        show(sDefaultTimeout);
        return false;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        
        
        int keyCode = event.getKeyCode();
        

        show(sDefaultTimeout);
        return super.dispatchKeyEvent(event);
    }

    
    @Override
    public void setEnabled(boolean enabled) {
       
        super.setEnabled(enabled);
    }


    public class PlayVideoTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			int progressOfSeekBar = 0;
			while (progressOfSeekBar <= maxSeekBarValue) {
				while (progressOfSeekBar <= maxSeekBarValue) {
					progressOfSeekBar = mSeekBarOne.getProgress();
					mSeekBarOne.setProgress(progressOfSeekBar + 1);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (progressOfSeekBar >= maxSeekBarValue) {
					mSeekBarOne.setProgress(minSeekBarValue);
					mPlayer.seekTo(minSeekBarValue);
					progressOfSeekBar = minSeekBarValue;
				}
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		}

	}
   

   
    
    public interface MediaPlayerControl {
        void    start();
        void    pause();
        int     getDuration();
        int     getCurrentPosition();
        void    seekTo(int pos);
        boolean isPlaying();
        int     getBufferPercentage();
        boolean canPause();
        boolean canSeekBackward();
        boolean canSeekForward();
        boolean isFullScreen();
        void    toggleFullScreen();
    }
    
    private static class MessageHandler extends Handler {
        private final WeakReference<VideoOptionsView> mView; 

        MessageHandler(VideoOptionsView view) {
            mView = new WeakReference<VideoOptionsView>(view);
        }
        @Override
        public void handleMessage(Message msg) {
            VideoOptionsView view = mView.get();
            if (view == null) {
                return;
            }
            
            switch (msg.what) {
                case FADE_OUT:
                    //view.hide();
                    break;
               
            }
        }
    }

	
}